package com.chenix.aicodehelper.controller;

import com.chenix.aicodehelper.Ai.AiCoderHelperService;
import com.chenix.aicodehelper.Ai.AiCoderhelper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;


@RestController
@RequestMapping("/ai")
@Slf4j
public class AiController {

    @Resource
    private AiCoderHelperService aiCoderHelperService;
    @GetMapping("/chat")
    public Flux<ServerSentEvent<String>> chat(@RequestParam("memoryId") String memoryId, @RequestParam("userMessage")String userMessage) {
        Flux<String> stringFlux = aiCoderHelperService.chatStream(memoryId, userMessage);
        /*Flux<ServerSentEvent<String>> serverSentEventStream = stringFlux.map(
                data -> ServerSentEvent.builder(data).build()
        );*/
        Flux<ServerSentEvent<String>> serverSentEventStream = stringFlux
                // 先记录数据（在映射为ServerSentEvent之前）
                .doOnNext(data -> log.info("原始数据: {}", data))
                .map(data -> ServerSentEvent.builder(data).build())
                // 记录转换后的ServerSentEvent数据
                .doOnNext(sse -> log.info("SSE数据: {}", sse.data()));
        return serverSentEventStream;

    }
}
